package com.example.back.service;

import com.example.back.entity.Like;
import com.example.back.entity.Notice;
import com.example.back.mapper.LikeMapper;
import com.example.back.mapper.NoticeMapper;
import com.example.back.mapper.PostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


@Service
public class LikeService {
    @Autowired
    private LikeMapper likeMapper;
    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private PostMapper postMapper;
    public int addLike(Like like)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int result = likeMapper.addLike(like);
        if(result>0){
            int postUserId = postMapper.queryPostById(like.getPostId()).getUserId();
            Notice notice = new Notice();
            notice.setUserId(postUserId);
            notice.setTriggerUserId(like.getUserId());
            notice.setPostId(like.getPostId());
            notice.setTime(sdf.format(new Date()));
            notice.setText("用户 " + like.getUserId() + " 点赞了您的帖子 " + like.getPostId());
            notice.setType("like");
            noticeMapper.addNotice(notice);
        }
        return result;
    }
    public int deleteLike(Integer postId, Integer userId)
    {
        return likeMapper.deleteLike(postId,userId);
    }
    public int updateLike(Like like)
    {
        return likeMapper.updateLike(like);
    }
    public ArrayList<Like> queryLike(Like like)
    {
        return likeMapper.queryLike(like);
    }

    // 查询用户是否已点赞该帖子
    public Like getLikeByUserAndPost(Integer postId, Integer userId) {
        return likeMapper.getLikeByUserAndPost(postId, userId);
    }

    // 统计帖子的点赞数
    public int countLikeByPostId(Integer postId){
        return likeMapper.countLikeByPostId(postId);
    }
    public int countUserLikes(Integer userId){
        return likeMapper.countUserLikes(userId);
    }
}
